#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode *next;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class longestZigPath {
public:
    int longestZigZag(TreeNode* root) {
        ans = 0;
        dfs(root->left, true, 1);
        dfs(root->right, false, 1);
        return ans;
    }

    void dfs(TreeNode* root, bool isLeft, int dist) {
        if (root == NULL)
            return;
        ans = max(ans, dist);
        if (isLeft) {
            dfs(root->right, false, dist + 1);
            dfs(root->left, true, 1);
        }
        else {
            dfs(root->left, true, dist + 1);
            dfs(root->right, false, 1);
        }
    }
private:
    int ans;
};